package top.dashuizhuyu.mdx;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JOptionPane;

public class MDX {

	static Scanner scanner = new Scanner(System.in);

	private static final String REG_EXP_IMG_POINT = "!\\[\\S+\\)";
	private static final String REG_EXP_IMG_PATH = "(?<=\\()[^\\)]+";

	public static void main(String[] args) throws IOException {
		
		if (args.length < 1) {
			System.out.println("请输入原文件路径参数！");
			Tips.message("请输入原文件路径参数！",JOptionPane.ERROR_MESSAGE);
			return;
		}
		String filePathS = args[0];
//		 String filePathS = "C:\\Users\\Administrator\\Desktop\\test.md";
		
		// 加载配置文件，获取输出路径
		Properties properties = new Properties();
		InputStream in = MDX.class.getClassLoader().getResourceAsStream("config.properties");
		properties.load(in);
		in.close();
				
		String filePathTCfg = properties.getProperty("filePathT");
		String filePathT = "";
		if (filePathTCfg == null) {
			// filePathT = filePathS + "x";
			filePathT = filePathS.replace(".md", ".base64.md");
		} else {
			filePathT = new String(filePathTCfg.getBytes("ISO-8859-1"), "UTF-8");
			filePathT = filePathT + filePathS.substring(filePathS.lastIndexOf("\\") + 1);
		}

		String fileContent = getFileContent(filePathS);

		// while(args[0] != null){
		try {
			mdx(filePathS, filePathT, fileContent);
			Tips.message("已生成MD-BASE64文件到：" + filePathT,JOptionPane.OK_CANCEL_OPTION);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Tips.message(e.getMessage(),JOptionPane.ERROR_MESSAGE);
		}
		// }

	}
	
	public static void mdx(String filePathS, String filePathT, String fileContent) throws Exception {
		List<String> imgPointArr = new ArrayList<>();
		Matcher matcher = Pattern.compile(REG_EXP_IMG_POINT).matcher(fileContent);
		while (matcher.find()) { // 此处find（）每次被调用后，会偏移到下一个匹配
			imgPointArr.add(matcher.group());// 获取当前匹配的值
		}

		Map<String, String> map = new LinkedHashMap<>();
		Pattern pattern = Pattern.compile(REG_EXP_IMG_PATH);
		for (int i = 0; i < imgPointArr.size(); i++) {
			String oldImgStr = imgPointArr.get(i);
			matcher = pattern.matcher(oldImgStr);
			if (matcher.find()) {
				String imgPath = matcher.group();
				imgPath = Image.pathAbsolute(filePathS, imgPath);
				System.out.println((i + 1) + ":" + imgPath);
				map.put(oldImgStr, Image.image2Base64(imgPath));
			}
		}

		Set<String> keySet = map.keySet();
		for (String key : keySet) {
			fileContent = fileContent.replace(key, "<img src='data:image/png;base64," + map.get(key) + "'> \n");
		}

		FileOutputStream outputStream = new FileOutputStream(filePathT);
		OutputStreamWriter osw = new OutputStreamWriter(outputStream, "UTF-8");
		osw.write(fileContent);
		osw.flush();
		osw.close();
		outputStream.close();
	}

	/**
	 * 读取MD文件的内容
	 * 
	 * @param filePath
	 *            文件路径
	 * @return 字符串
	 * @throws FileNotFoundException
	 * @throws UnsupportedEncodingException
	 */
	public static String getFileContent(String filePath) throws FileNotFoundException, UnsupportedEncodingException {
		File file = new File(filePath);
		FileInputStream fin = new FileInputStream(file);
		InputStreamReader isr = new InputStreamReader(fin, "UTF-8");
		BufferedReader reader = null;
		StringBuffer sbf = new StringBuffer();
		try {
			reader = new BufferedReader(isr);
			String tempStr;
			while ((tempStr = reader.readLine()) != null) {
				sbf.append(tempStr + "\n");
			}
			reader.close();
			return sbf.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return sbf.toString();
	}

}
